package ngames.com.sushitv.core;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import ngames.com.sushitv.activity.LoginActivity;
import ngames.com.sushitv.api.Api;
import ngames.com.sushitv.api.ApiResponse;
import ngames.com.sushitv.api.JSONResolve;
import ngames.com.sushitv.entity.ResetPasswordInfo;
import ngames.com.sushitv.entity.UserInfo;
import ngames.com.sushitv.net.okhttp.callback.RequestCallBackJSON;
import ngames.com.sushitv.tools.Constants;
import ngames.com.sushitv.tools.LogUtil;
import ngames.com.sushitv.tools.MD5;
import ngames.com.sushitv.tools.PreferenceManager;

/**
 * Created by Jeffrey on 2016/7/26.
 */
public class UserService {
    private Context mContext;
    private Api mApiImpl;
    private UserInfo mUserInfo;
    private String mUserID;
    private Activity mCurrentActivity;

    public UserService(Context context, Api apiImpl) {
        mContext = context;
        mApiImpl = apiImpl;
    }

    public void setUserInfo(UserInfo userInfo) {
        mUserInfo = userInfo;
    }

    public void setCurrentActivity(Activity activity) {
        mCurrentActivity = activity;
    }

    public UserInfo getUserInfo() {
//        if (mUserInfo == null || TextUtils.isEmpty(mUserInfo.getUserID())) {
//            mUserInfo = PreferenceManager.getInstance().getUserInfo();
//        }
        return mUserInfo;
    }

    public boolean needLogin(boolean toLogin) {
        if (mUserInfo == null) {
            getLoginInfo();
        }
        if (mUserInfo != null && mUserInfo.getExpired() > System.currentTimeMillis()) {
            return false;
        }
        if (toLogin) {
            mCurrentActivity.startActivity(new Intent(mCurrentActivity, LoginActivity.class));
        }
        return true;
    }

    public UserInfo getLoginInfo() {
        mUserInfo = PreferenceManager.getInstance().getLoginInfo();
        return mUserInfo;
    }

    public void setLoginInfo(String type, UserInfo userInfo) {
        userInfo.setAccountType(type);
        String token = userInfo.getToken();
        Constants.APP_TOKEN = token == null ? "" : token;
        long e = userInfo.getExpired();
        LogUtil.d("UserService", "setLoginInfo() Expired = " + e);
        userInfo.setExpired(e * 1000 + System.currentTimeMillis());
        mUserInfo = userInfo;
        PreferenceManager.getInstance().saveLoginInfo(userInfo);
    }

    public void login(String type, String email, String area, String phone, String password, final ModelCallback<UserInfo> listener) {
        mApiImpl.login(type, email, area, phone, MD5.toMD5(password), new RequestCallBackJSON<UserInfo>() {
            @Override
            public ApiResponse<UserInfo> onParse(String responseStr) {
                return JSONResolve.resolveGSONData(responseStr, UserInfo.class);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(UserInfo obj) {
                setLoginInfo(Constants.ACCOUNT_TYPE_APP, obj);
                listener.onSuccess(obj);
            }
        });
    }

    public void loginFB(UserInfo userInfo, final ModelCallback<UserInfo> listener) {
        userInfo.setAccountType(Constants.ACCOUNT_TYPE_FB);
        String fbID = userInfo.getUid();
        String email = userInfo.getEmail();
        mApiImpl.loginFB(fbID, email, new RequestCallBackJSON<UserInfo>() {
            @Override
            public ApiResponse<UserInfo> onParse(String responseStr) {
                return JSONResolve.resolveGSONData(responseStr, UserInfo.class);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(UserInfo obj) {
                setLoginInfo(Constants.ACCOUNT_TYPE_FB, obj);
                listener.onSuccess(obj);
            }
        });
    }

    public void register(UserInfo userInfoFB, String name, String email, String password, final ModelCallback<UserInfo> listener) {
        final String type;
        String fbID = null;
        String fbEmail = null;
        String fbAvatar = null;
        if (userInfoFB == null) {
            type = Constants.ACCOUNT_TYPE_APP;
        } else {
            type = Constants.ACCOUNT_TYPE_FB;
            fbID = userInfoFB.getUid();
            fbEmail = userInfoFB.getEmail();
            fbAvatar = userInfoFB.getAvatar();
        }
        mApiImpl.register(type, fbID, fbEmail, fbAvatar, name, email, MD5.toMD5(password), new RequestCallBackJSON<UserInfo>() {
            @Override
            public ApiResponse<UserInfo> onParse(String responseStr) {
                return JSONResolve.resolveGSONData(responseStr, UserInfo.class);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(UserInfo obj) {
                setLoginInfo(type, obj);
                listener.onSuccess(obj);
            }
        });
    }

    public void registerPhone(String sms_key, String sms_code, String name, String password, String area, String phone, final ModelCallback<UserInfo> listener) {
        mApiImpl.registerPhone(sms_key, sms_code, name, MD5.toMD5(password), area, phone, new RequestCallBackJSON<UserInfo>() {
            @Override
            public ApiResponse<UserInfo> onParse(String responseStr) {
                return JSONResolve.resolveGSONData(responseStr, UserInfo.class);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(UserInfo obj) {
                setLoginInfo(Constants.ACCOUNT_TYPE_APP, obj);
                listener.onSuccess(obj);
            }
        });
    }

    public void refreshToken() {
        if (needLogin(false)) {
            return;
        }
        String refreshToken = mUserInfo.getRefreshToken();
        if (TextUtils.isEmpty(refreshToken)) {
            return;
        }
        mApiImpl.refreshToken(refreshToken, new RequestCallBackJSON<UserInfo>() {
            @Override
            public ApiResponse<UserInfo> onParse(String responseStr) {
                return JSONResolve.resolveGSONData(responseStr, UserInfo.class);
            }

            @Override
            public void onFailure(String code, String msg) {

            }

            @Override
            public void onSuccess(UserInfo obj) {
                setLoginInfo(mUserInfo.getAccountType(), obj);
            }
        });
    }

    public void forgotPassword(String email, final ModelCallback<Void> listener) {
        mApiImpl.forgotPassword(email, new RequestCallBackJSON<Void>() {
            @Override
            public ApiResponse<Void> onParse(String responseStr) {
                return JSONResolve.resolveCode(responseStr);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(Void obj) {
                listener.onSuccess(obj);
            }
        });
    }

    public void forgotPasswordPhone(String area, String phone, String sms_key, String sms_code, final ModelCallback<ResetPasswordInfo> listener) {
        mApiImpl.forgotPasswordPhone(area, phone, sms_key, sms_code, new RequestCallBackJSON<ResetPasswordInfo>() {
            @Override
            public ApiResponse<ResetPasswordInfo> onParse(String responseStr) {
                return JSONResolve.resolveGSONData(responseStr, ResetPasswordInfo.class);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(ResetPasswordInfo obj) {
                getUserInfo().setResetPasswordInfo(obj);
                listener.onSuccess(obj);
            }
        });
    }

    public void resetPassword(String password, final ModelCallback<Void> listener) {
        ResetPasswordInfo info = getUserInfo().getResetPasswordInfo();
        if (info == null) {
            listener.onFailure("", "");
            return;
        }
        mApiImpl.resetPassword(info.getArea(), info.getPhone(), info.getResetToken(), MD5.toMD5(password), new RequestCallBackJSON<Void>() {
            @Override
            public ApiResponse<Void> onParse(String responseStr) {
                return JSONResolve.resolveCode(responseStr);
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(Void obj) {
                listener.onSuccess(obj);
            }
        });
    }

    /**
     * 验证name、email是否被注册;type:email和name
     */
    public void isRegistered(String type, String value, final ModelCallback<Void> listener) {
        mApiImpl.isRegistered(type, value, new RequestCallBackJSON<Void>() {
            @Override
            public ApiResponse<Void> onParse(String responseStr) {
                return JSONResolve.resolveCode(responseStr);
            }

            @Override
            public void onFailure(String code, String msg) {

            }

            @Override
            public void onSuccess(Void obj) {

            }
        });
    }

    public void sendSms(String type, String phone, final ModelCallback<String> listener) {
        mApiImpl.sendSms(type, phone, new RequestCallBackJSON<String>() {
            @Override
            public ApiResponse<String> onParse(String responseStr) {
                return JSONResolve.dataString(responseStr, "key");
            }

            @Override
            public void onFailure(String code, String msg) {
                listener.onFailure(code, msg);
            }

            @Override
            public void onSuccess(String obj) {
                listener.onSuccess(obj);
            }
        });
    }
}
